package com.lanhai.zhonglai.report;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.gson.Gson;
import com.lanhai.zhonglai.utils.UploadTemplete;

/**
 * AGV位置上报
 * @author zhengwei
 *
 */
@Component
public class AgvStateThread {
	  boolean running;
	  Thread th;
	  long sleep;
	String url;
	Gson gson;

	@Autowired
	AgvStateMap stateMap;

	public AgvStateThread() {
		gson=new Gson();
		url="http://127.0.0.1:8100/api/Report/uploadAgv";
		sleep=2000;
	}

	public void Start(int second) {
		running=true;
		if(second>0&&second<=10) {
			sleep=1000*second;
		}

		th=new Thread() {
			@Override
			public void run() {
				while (running) {
					List<AgvStateBean> ls = stateMap.getAll();
					if (ls.size() > 0) {
						UploadTemplete<AgvStateBean> tp = new UploadTemplete<AgvStateBean>();
						tp.setList(ls);

						String json = gson.toJson(tp);
						post(json);
					}

					try {
						Thread.sleep(sleep);
					} catch (InterruptedException e) {

					}
				}

			}

		};
		th.start();
	}


	void post(String json) {
		try {
			HttpClient client = HttpClient.newHttpClient();
			HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url))
					.header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(json)).build();

			HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
			if (response.statusCode() != 200) {
				  //System.out.println(response.statusCode() + "");

			} else {
				//  System.out.println(json);
			}

		} catch (Exception ex) {
			 //System.out.println(json);
				//ex.printStackTrace();
		}

	}

	public void Stop() {
		running=false;
		try {
			th.interrupt();
			th=null;
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
}
